var tbody = document.querySelector('tbody');
var input = document.querySelector('input');
var search = document.querySelector('.search');

var url = "http://localhost:3008";
var getAPI = "/api/student/getStudent";
var removeAPI = "/api/student/removeStudent";


getData(url + getAPI, {}, all);

function all(data) {
    data.forEach(function(value) {
        tbody.innerHTML += `
        <tr>
            <td>${value.id}</td>
            <td>${value.clazz}</td>
            <td>${value.name}</td>
            <td>${value.gender}</td>
            <td>${value.age}</td>
            <td>${value.tel}</td>
            <td>${value.hobby}</td>
            <td>${value.address}</td>
            <td>${value.remark}</td>
            <td>${value.date}</td>  
            <td>
                <button class="edit">修改</button>
                <button class="del">删除</button>
            </td>
        </tr>
        `
        var edit = document.querySelectorAll('.edit');
        var del = document.querySelectorAll('.del');

        // 修改
        edit.forEach(function(value) {
            value.addEventListener('click', function() {
                location.assign('./page/add.html?id=' + value.parentNode.parentNode.children[0].innerText);
            })
        })

        // 删除
        del.forEach(function(value) {
            value.addEventListener('click', function() {
                getData(url + removeAPI, { id: value.parentNode.parentNode.children[0].innerText }, alt);

                function alt() {
                    alert("删除成功");
                    location.reload();
                }
            })
        })
    })
}

// 搜索
search.onclick = function() {
    // 先置空
    tbody.innerHTML = '';
    if (input.value.trim()) {
        getData(url + getAPI, { name: input.value.trim() }, all);
    } else {
        getData(url + getAPI, {}, all);
    }
}